<?php
namespace app\index\model;

use think\Model;

class Charge extends Model
{   
    public function addOrder($order_info){
        //根据锁的id获取杆柜的id
        $box_id    = db('Lock')->where('id',$order_info['lock_id'])->value('box_id');
        //根据柜子的id，获取球房的id与球房的名称
        $order_info['club_id']   = db('box')->where('id',$box_id)->value('club_id');
        $order_info['club_name'] = db('club')->where('id',$order_info['club_id'])->value('name');
        
        $order_info['out_trade_no'] = date('YmdHis',time()).getRandCode(6);//商户的订单号
        
        //用户表中添加商户订单号
        if(!db('user')->where('id',$order_info['user_id'])->value('deposit')){
             db('user')->where('id',$order_info['user_id'])->update(array('out_trade_no'=>$order_info['out_trade_no']));
        }
       

        return db('charge_log')->insertGetId($order_info);
    }

      //统一下单接口，获取package
    public function pay_place_order($user_id,$amount,$out_trade_no){
        $prepay = array(
            'appid'            => 'wxa641018b058e4ac9', //小程序qppid
            'body'             => '高端手工台球杆', //支付商品描述
            'mch_id'           => '1326035601', 
            'nonce_str'        => getRandCode(16),//生成随机的32位字符串
            'notify_url'       => 'https://wxa.chaojisales.com/index/pay/index',  //通讯地址
            'openid'           =>  db('user')->where('id',$user_id)->value('openid'),
            'out_trade_no'     => $out_trade_no,//商户的订单号
            'spbill_create_ip' => getIP(),//客户端的IP
            'total_fee'        => $amount,//总金额
            'trade_type'       => 'JSAPI'
        );
      
        $xml = '<xml>
                   <appid>'.$prepay['appid'].'</appid>
                   <body>'.$prepay['body'].'</body>
                   <mch_id>'.$prepay['mch_id'].'</mch_id>
                   <nonce_str>'.$prepay['nonce_str'].'</nonce_str>
                   <notify_url>'.$prepay['notify_url'].'</notify_url>
                   <openid>'.$prepay['openid'].'</openid>
                   <out_trade_no>'.$prepay['out_trade_no'].'</out_trade_no>
                   <spbill_create_ip>'.$prepay['spbill_create_ip'].'</spbill_create_ip>
                   <total_fee>'.$prepay['total_fee'].'</total_fee>
                   <trade_type>'.$prepay['trade_type'].'</trade_type>
                   <sign>'.$this->MakeSign($prepay).'</sign>
                </xml>';
       //调用api，自定义对参数进行处理，改请求方式是自定义方式 
        $xml_result = httpRequest('https://api.mch.weixin.qq.com/pay/unifiedorder','POST',$xml);
        
        $result     = json_decode(json_encode(simplexml_load_string($xml_result, 'SimpleXMLElement', LIBXML_NOCDATA)),true);
      
        $data['nonce_str'] = $prepay['nonce_str'];
        $data['prepay_id'] = $result['prepay_id'];
        $data['nonce_str'] = $prepay['nonce_str'];
        $data['timeStamp'] = time();   
        return $this->getPaySign($data);
    }

     public function getPaySign($data){
        $result['pay_sign']   = strtoupper(md5("appId=wxa641018b058e4ac9&nonceStr=".$data['nonce_str']."&package=prepay_id=".$data['prepay_id']."&signType=MD5&timeStamp=".$data['timeStamp']."&key=d57f65ebb69106cd68d1aacd7b8616d7"));
        $result['time_stamp'] = (string)time();
        $result['nonce_str']  = $data['nonce_str'];
        $result['prepay_id']  = $data['prepay_id'];
        return $result;
    }

    public function MakeSign($prepay)
    {
        //签名步骤一：按字典序排序参数
        ksort($prepay);
        $string = $this->ToUrlParams($prepay);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=d57f65ebb69106cd68d1aacd7b8616d7";
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($prepay)
    {
        $buff = "";
        foreach ($prepay as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }


   /**
     * 用户开锁成功以后插入计费信息
     * @param int $lock_id 必填,锁得id
     * @param int $user_id 必填，用户的id
     * @return stauts
     */
    public function StartBilling($user_id,$lock_id,$form_id){

        //根据锁的id获取杆柜的id
        $box_id    = db('Lock')->where('id',$lock_id)->value('box_id');
        //根据柜子的id，获取球房的id与球房的名称
        $club_id   = db('box')->where('id',$box_id)->value('club_id');
        $club_name = db('club')->where('id',$club_id)->value('name');

        $insert_info['user_id']      = $user_id;
        $insert_info['start_time']   = time();
        $insert_info['club_id']      = $club_id;
        $insert_info['club_name']    = $club_name;
        $insert_info['lock_id']      = $lock_id;
        $insert_info['form_id']      = $form_id;
        return db('charge_log')->insertGetId($insert_info);
    } 

    /**
     * 用户还杆成功以后进行结算
     * @param int $lock_id 必填,锁得id
     * @param int $user_id 必填，用户的id
     * @return stauts
     */

    public function endBilling($number,$user_id){
    	$User    = db('user');
    	$Charge  = db('charge_log');

    	//查询到未结算的信息
    	
        $where['user_id']  = $user_id;
    	$where['end_time'] = 0;
        $where['is_pay']   = 1;

    	$charge_info = $Charge->where($where)->order('id desc')->find();

        $update_info['end_time'] = time();


    	//计算用户使用球杆的时间 s
        $update_info['duration'] = $charge_info['start_time'] ?  ($update_info['end_time'] - $charge_info['start_time']) : 0;
        
        //if($user_feedback == 0){
            //获取每小时的单价费用
        $payment_info = db('payment_type')->where('status',1)->field('price,priceunit')->find();

        $unit_price   = $payment_info['price']/$payment_info['priceunit'];//每分钟多少钱
        
        //用户使用分钟
        $use_minutes = ceil($update_info['duration']/60);

        //$update_info['amount'] = round($use_minutes*$unit_price,2);
        // }else{
        //     $update_info['amount'] = 0.00;
        // }
       
        
        $update_info['order_number'] = date('YmdHis',$update_info['end_time']).$user_id;
        //用户账户余额扣钱
        //$money = $User->where('id',$user_id)->value('money');
      
        //$new_money = $money-$update_info['amount'];
     
        $result_1 = $Charge->where('id',$charge_info['id'])->update($update_info);
        //$result_2 = $User->where('id',$user_id)->update(array('money'=>$new_money));

        $this->addForce($user_id,$use_minutes);
         
        if($result_1){
        	$data['status'] = 1; 
        	//$data['money']  = $new_money;
            $data['order_info'] = $update_info;//订单的编号
            $data['order_info']['amount'] = $charge_info['amount'];
            $this->sendMessageInfo($charge_info['form_id'], $data['order_info'],$user_id);

        }else{
        	$data['status'] = 0;
        	$data['info']   = '扣费失败！';
        }
        return $data;
    }

    //计算用户战力
    private function addForce($user_id,$force){
        $force_info = db('force_statistics')->where('user_id',$user_id)->field('force_total,force_best')->find();
        $update_info['force_total'] = intval($force_info['force_total']+$force);
        if($force_info['force_best'] < $force){
            $update_info['force_best'] = $force;
        }

        db('force_statistics')->where('user_id',$user_id)->update($update_info);
    }

      //发送微信小程序通知
    private function sendMessageInfo($form_id,$order_info,$user_id){
        $return_time = date('Y-m-d H:i',$order_info['end_time']);
        $duration    = formatDuration($order_info['duration']);
        $into        = "恭喜您用杆成功，本次的消费金额：{$order_info['amount']}元";
        //获取用户的open_id
        $openid = db('user')->where('id',$user_id)->value('openid');
        $message_info['touser']           = $openid;
        $message_info['template_id']      = 'j-4aHxsLUQV9MPrQnS0gooE00zrmQ11egRzbJElpCIE';
        $message_info['page']             = 'pages/index/index';
        $message_info['form_id']          = $form_id;

       // $message_info['data']['keyword1'] = array('value'=>$order_info['order_number'],'color'=>"#173177");
        $message_info['data']['keyword1'] = array('value'=>$return_time,'color'=>"#173177");
        $message_info['data']['keyword2'] = array('value'=>$duration,'color'=>"#173177");
        $message_info['data']['keyword3'] = array('value'=>$into ,'color'=>"#173177");
       
        $access_token = getAccessToken();
        $url    = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";
       
        $result = httpRequest($url,'POST',json_encode($message_info));
    
    }

    //获取用户的消费使用记录
    public function getUserCharge($user_id){
    	$where['user_id']  = $user_id;
    	$where['is_pay'] = 1;
    	$user_charge = db('charge_log')->where($where)->order('end_time desc')->select();
    	return $user_charge;
    }
    //验证该用杆消费记录是否结算
    public function checkChargeISEnd($charge_id){
        return db('charge_log')->where('id',$charge_id)->value('end_time') > 0 ? true : false;
    }

}